package com.tticar.invmanager.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tticar.invmanager.common.Enum.CodeType;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.utils.ExcelUtils;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.entity.WRelativeUnit;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.service.ICodeCounterService;
import com.tticar.invmanager.service.IWRelativeUnitService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 往来客户 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-07-08
 */
@Controller
@RequestMapping("/wRelativeUnit")
public class WRelativeUnitController extends BaseController {

    private final String[] titles = {"名称（必填）", "简称", "客户/供应商（必填）", "一级会员/二级会员", "联系人", "联系电话", "地址"};

    @Autowired
    private IWRelativeUnitService wRelativeUnitService;

    @Autowired
    private ICodeCounterService codeCounterService;
    @PostMapping
    @ResponseBody
    public MyResponseBody post(WRelativeUnit wRelativeUnit) {
        if(StringUtils.isNotEmpty(wRelativeUnit.getHelpCode())) {
            if(!wRelativeUnit.getHelpCode().matches("[a-zA-Z]+")) {
                throw new MyServiceException("助记码必须是英文大写字母");
            }
            wRelativeUnit.setHelpCode(wRelativeUnit.getHelpCode().toUpperCase());
        }
        if (wRelativeUnit.getId() !=null && wRelativeUnit.getStatus() != 0) {
            List<Long> longs = wRelativeUnitService.queryOrderIdByRelativeId(wRelativeUnit.getId());
            if (longs.size() > 0) {
                throw new MyServiceException("该客户/供应商存在为完成的订单，不能禁用");
            }
        }
        if (wRelativeUnit.getId() == null) {
            String code = "";
            //1客户 2供应商
            if (wRelativeUnit.getRproperty() == 1) {
                 code = codeCounterService.getCode(CodeType.KH, "", 6);
            }
            if (wRelativeUnit.getRproperty() == 2) {
                 code = codeCounterService.getCode(CodeType.GYS, "", 4);
            }
            wRelativeUnit.setCode(code);
        }

        if(StringUtils.isEmpty(wRelativeUnit.getHelpCode())) {
            wRelativeUnit.setHelpCode("");
        }
        if(StringUtils.isEmpty(wRelativeUnit.getContactor())) {
            wRelativeUnit.setContactor("");
        }
        if(StringUtils.isEmpty(wRelativeUnit.getTel())) {
            wRelativeUnit.setTel("");
        }
        if(StringUtils.isEmpty(wRelativeUnit.getAddr())) {
            wRelativeUnit.setAddr("");
        }
        wRelativeUnitService.insertOrUpdate(wRelativeUnit);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        wRelativeUnitService.delete(ids);
        return responseBody;
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(wRelativeUnitService.selectById(id));
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(WRelativeUnit wRelativeUnit, ModelMap modelMap) {
        modelMap.put("id", wRelativeUnit.getId());
        return "/wRelativeUnit/wRelativeUnit_edit";
    }

    @GetMapping("list")
    @ResponseBody
    public Page list(WRelativeUnit wRelativeUnit, MyPage<WRelativeUnit> page) {
        if(wRelativeUnit.getRproperty() == null) {
            wRelativeUnit.setRproperty(1);
        }
        return wRelativeUnitService.selectPage(wRelativeUnit, page);
    }

    @PostMapping("supplier/list")
    @ResponseBody
    public List<Map<String, Object>> supplierList(WRelativeUnit wRelativeUnit, MyPage<WRelativeUnit> page) {
        wRelativeUnit.setRproperty(2);
        Page tmp = wRelativeUnitService.selectPage(wRelativeUnit, page);
        return (List<Map<String, Object>>) tmp.getRecords();
    }

    @PostMapping("supplier/listNotPage")
    @ResponseBody
    public List supplierList(WRelativeUnit wRelativeUnit) {
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("rproperty", 2);
        wrapper.eq("status", 0);
        List<WRelativeUnit> wRelativeUnits = wRelativeUnitService.selectList(wrapper);
        return wRelativeUnits;
    }
    @PostMapping("custom/listNotPage")
    @ResponseBody
    public List customList(WRelativeUnit wRelativeUnit) {
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("rproperty", 1);
        wrapper.eq("status", 0);
        List<WRelativeUnit> wRelativeUnits = wRelativeUnitService.selectList(wrapper);
        return wRelativeUnits;
    }

    @GetMapping
    public String index() {
        return "/wRelativeUnit/wRelativeUnit";
    }

    @GetMapping("customer")
    public String customer() {
        return "/wRelativeUnit/customer";
    }

    @GetMapping("importExcel")
    public String importExcel(ModelMap modelMap) {
        return "/wRelativeUnit/importExcelForRelative";
    }

    /**
     * 导入Excel
     * @param excelFile
     * @return
     */
    @PostMapping("saveExcel")
    @ResponseBody
    public MyResponseBody saveExcel(@RequestParam("excelFile") MultipartFile excelFile) {
        MyResponseBody responseBody = MyResponseBody.success();
        try {
            List<List<String>> listByExcel = ExcelUtils.getExcelSheet(excelFile, titles);
            wRelativeUnitService.insertExcel(listByExcel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyServiceException(e.getMessage());
        }
        return responseBody;
    }

    /**
     * 下载Excel模板
     * @return
     */
    @GetMapping("downLoadExcel")
    @ResponseBody
    public void downLoadExcel(HttpServletResponse response) {

        HSSFWorkbook wb = null;
        OutputStream output = null;
        try {
            wb = ExcelUtils.createExcel(titles);
            output = response.getOutputStream();
            response.addHeader("Content-Disposition", "inline;filename="+java.net.URLEncoder.encode("往来客户导入Excel模板.xls"));
            response.setContentType("application/msexcel");
            wb.write(output);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (output !=null) {
                    output.close();
                }
                if (wb != null) {
                    wb.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
